JS Utility Library Documentation
Collection of libraries with classes and functions for JavaScript

List of functions included in Utility
{
convertToBool: "accurately converts a value to a boolean, accepts int, string and boolean",
convertToNumber: "accurately converts a value to a number, accepts int, string and boolean",
currencyToDecimal: "converts a currency string to a decimal number",
dateFormat: "formats a date object to a specified format string",
decimalToCurrency: "converts a decimal number to a currency string",
emptyOrValue: "returns a default value if a given value is empty or undefined, uses isEmpty()",
getGoogleMapsAddress: "gets a formatted address string for a location using the Google Maps API",
formatPhoneNumber: "formats a phone number string to a standardized format",
getDynamicId: "generates a unique ID string based on a prefix, timestamp and a random number",
getRandomId: "generates a random ID string",
includes: "checks if a collection (object|string|array) includes a given value",
isNumber: "checks if a given value is a number (that includes string numbers and floats)",
isEmpty: "checks if a given value is empty, checks arrays, objects, etc",
logThis: "logs a message to the console with a specified prefix",
openGoogleMapsAddress: "opens Google Maps in a new tab with a specified address",
toCurrency: "formats a number to a currency string",
toDollarString: "formats a number to a dollar string",
typeOf: "gets the type of a value and can also return simple comparisons. For more advanced type-checking, use the 'typeCheck' library https://github.com/knighttower/JsTypeCheck",
instanceOf: "gets the instance of a value and can also return simple comparisons",
validateEmail: "validates an email address string to ensure it is in a valid format",
validatePhone: "validates a phone number string to ensure it is in a valid format"
makeArray: "converts a value to an array, if it is not already an array"
}
You can see the src with github and explore the functions by using the "symbols explorer" from Github here
List of functions included in PowerHelpers
{
addQuotes: "adds quotes around a string",
cleanStr: "removes delimiters from a string",
convertKeysToSymbols: "converts object keys to symbols",
findAndReplaceInArray: "finds and replaces a value in an array",
findNested: "finds arrays or objects in a string",
fixQuotes: "replaces single quotes with double quotes in a string",
getArrObjFromString: "extracts an array or objects from a string",
getDirectivesFromString: "extracts directives from a string",
getMatchBlock: "extracts a block of text between two delimiters",
getMatchInBetween: "extracts a substring between two delimiters",
removeQuotes: "removes quotes from a string",
setExpString: "sets a regular expression string based on a given pattern",
setLookUpExp: "sets a regular expression string for looking up a value in an object",
startAndEndWith: "looks for a string that starts and ends with a given pattern",
setWildCardString: "sets a wildcard at the beginning, end, or middle of a string",
wildCardStringSearch: "searches for a string using wildcards"
getObjectFromPath: "gets an object from a path",
}
You can see the src with github and explore the functions by using the "symbols explorer" from Github here
Installation
The library is standalone (via browser script tag, loads the whole library) or modular, either the entire object or only a few functions since it is completely modular.
npm i @knighttower/utility
yarn add @knighttower/utility
In the browser
It loads as a 'window' object --> window.Utility
<script src="https://cdn.jsdelivr.net/npm/@knighttower/utility@latest/dist/browser/Utility.min.js"></script>
// in addition, you can also load other libraries
<script src="https://cdn.jsdelivr.net/npm/@knighttower/utility@latest/dist/browser/PowerHelpers.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@knighttower/utility@latest/dist/browser/DomObserver.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@knighttower/utility@latest/dist/browser/UrlHelper.min.js"></script>
//or ESM
<script src="https://esm.run/@knighttower/utility@latest/index.mjs"></script>
Files
File | Size |
---|
/PowerHelpers.js | 10.5 KiB |
/PowerHelpers.js.br | 3.49 KiB |
/PowerHelpers.js.gz | 3.78 KiB |
/Utility.js | 8.54 KiB |
/Utility.js.br | 3.13 KiB |
/Utility.js.gz | 3.46 KiB |
By default the "import" or "require", will load the indexes automatically. But, in case of wanting to use individual files or other specific formats, all Files are available in the dist folder as ESM, CJS, AMD, IIFE, Browser, UMD and System formats. For ESM + JS 'next', use the files in the src folder or import directly from the index.js file.
Bonus: Also included into this monorepo are files for use in NodeJS Projects, see the "nodeUtils" folder for more information.
Overview
Utility Tiny collection of mighty utility functions with extended functionality for common cases (only 4k gzip and ESM). It was created to address the need of repetive need of some very common functions without the need of loading entire libraries for just a few functions while providing extra functionality:
Ex: emptyOrValue(value) or emptyOrValue(value, default) checks if the value is empty or undefined and returns the value or a default value if empty. Very helpful when dealing with variables that may or may not have a value.
Ex: typeOf(value) or typeOf(value, 'string') or typeOf(value, 'string|number') checks the type of a value and can also return comparisons (can take piped).
Ex: convertToBool(value) converts a value to a boolean, accepts int, string and boolean. Typical Js Boolean() only accepts strings and booleans but not 'true', 'false' as string
PowerHelper was designed to work for other specific libraries, but the fucntions for regex and string manipulation were actually so good to use in other projects that it was decided to share as well here.
Other libraries are also included in the dist folder, but they are not yet documented here.
ProxyObject, UrlHelper, DomObserver, ElementHelper, NodeHelpers, ProxyClass
See via Github explorer:
ProxyObject
UrlHelper
DomObserver
ElementHelper
NodeHelpers
ProxyClass
Most functions here are extremely handy without the overhead of big libraries.
However, for other most advance features it is recomended to also use other libraries, like if you need extensive use of Money, date, numbers functions (ex. money.js, moment.js, validate.js, lodash, v8n.js, jquery, moderndash, etc)
It also Uses some features from other KnightTower packages:
JsObjectProxyHelper (deprecated) (it has now been merged into this library but still will be available as a standalone library)JsUrlHelper (deprecated) (it has now been merged into this library but still will be available as a standalone library)JsDomObserver (deprecated) (it has now been merged into this library but still will be available as a standalone library)JsPowerHelperFunctions (deprecated) (it has now been merged into this library but still will be available as a standalone library)
All functions are handy, but the most handy of all is "emptyOrValue" which helps to mitigate a lot of headaches when dealing with variables to know whether or not they have a value or even to set a default value when empty. From the PowerHelpers, there are a lot of regex and string functions that are very handy.
All Functions have also been Unit Tested and tests are in the source code if you want to experiment or see more examples.
Usage
import Utility from '@knighttower/utility';
import PowerHelpers from '@knighttower/utility';
import { functionThatYouWantToUse, otherFunction } from '@knighttower/utility';
import { Utility as yourCustomName } from '@knighttower/utility';
import { functionThatYouWantToUse } from 'https://cdn.jsdelivr.net/npm/@knighttower/utility@latest/index.mjs';
Or even better, use it along with Vite and Autoimport like:
import AutoImport from 'unplugin-auto-import/vite';
... plugins: [
AutoImport({ imports: [ { '@knighttower/utility': ['Utility'] }] }),
]
let something = Utility.theFunctionYouWantToUse();
Methods
Note:
Some of these docs are outdated. Please look via the built in Github Symbol explorer for a better experience and understanding of the functions.
PowerHelpers
Utility
DomObserver
UrlHelper
ProxyHelper
ElementHelper
// NodeHelpers are not yet documented nor included with the above pkg cause it is node only files, but it can be imported from @knighttower/utility/node/index.mjs (NodeHelpers)
NodeHelpers
getGoogleMapsAddress
Parameters
address
(String|Object): The address information either as a string or as an object with properties like address
, zip
, city
, state
, etc.
Return value
string
: A string containing the Google Maps URL generated from the given address.
Example or Usage
getGoogleMapsAddress('New York');
getGoogleMapsAddress({ address: 'New York', zip: '10001' });
getGoogleMapsAddress({ address: 'New York', city: 'NY', state: 'New York' });
openGoogleMapsAddress
Parameters
object
(String|Object): The address information either as a string or as an object.
Return value
Throws
- Error: If the address is invalid or not a string/object.
Example or Usage
openGoogleMapsAddress('New York');
openGoogleMapsAddress({ address: 'New York', zip: '10001' });
formatPhoneNumber
Parameters
phoneNumber
(string): The phone number to format.template
(string): The template to use for formatting.
Return value
string
: The formatted phone number.
Example or Usage
formatPhoneNumber('1234567890', '(000) 000-0000');
formatPhoneNumber('9876543210', '000-000-0000');
validatePhone
Parameters
phone
(string): The phone number to validate.
Return value
boolean
: Returns true
if phone number is valid, otherwise false
.
Example or Usage
validatePhone('1234567890');
validatePhone('(123) 456-7890');
validateEmail
Parameters
email
(string): The email to validate.
Return value
boolean
: Returns true
if email is valid, otherwise false
.
Example or Usage
validateEmail('test@test.com');
validateEmail('invalid-email');
getDynamicId
Parameters
Return value
string
: A unique id in the format kn__000000__000
.
Example or Usage
getDynamicId();
getRandomId
Parameters
Return value
Example or Usage
getRandomId();
dateFormat
Parameters
dateTime
(string): Raw date-time format.wTime
(boolean): If set, returns date with time as H:MM A.
Return value
Example or Usage
dateFormat('2201-01-01 16:15PM', true);
dateFormat('2201-01-01 16:15PM', false);
currencyToDecimal
Parameters
amount
(String|Number): The amount in currency format.
Return value
number
: The amount in decimal format.
Example or Usage
currencyToDecimal('$123.45');
currencyToDecimal('€100.00');
decimalToCurrency
Parameters
amount
(String|Number): The amount in decimal format.
Return value
number
: The amount in currency format.
Example or Usage
decimalToCurrency(123.45);
decimalToCurrency(100);
toCurrency
Parameters
amount
(String|Number): The amount to format.
Return value
number
: The formatted amount.
Example or Usage
toCurrency(123.45);
toCurrency(100);
toDollarString
Parameters
amount
(String|Number): The amount to format.
Return value
number
: The formatted amount as a string.
Example or Usage
toDollarString(2000);
toDollarString(2000000);
emptyOrValue
Parameters
value
(String|Number|Array|Object|Boolean): The value to test._default
(String|Number|Array|Object|Boolean): The default value to return if value
is empty.
Return value
mixed
: Returns the value if not empty, otherwise returns null or the default value.
Example or Usage
emptyOrValue('test', 'default');
emptyOrValue('', 'default');
isNumber
Parameters
value
(String|Number): The value to test.
Return value
bool|int
: Returns true
if value is a number, otherwise returns false
.
Example or Usage
isNumber(123);
isNumber('abc');
logThis
Parameters
obj
(Object): The object to log.
Return value
Example or Usage
logThis('test');
logThis({ key: 'value' });
number
: The amount in decimal format.
Dependencies
Lodash: for utility functions (deprecated)
License
This project is licensed under the MIT License.
Checkout more cool stuff at https://knighttower.io/